﻿using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class CreateHeros : MonoBehaviour
{
    public GameObject[] towers;
    public GameObject turretPrefab_first; // 炮塔的预制体
    public GameObject turretPrefab_none;
    private GameObject turretInstance; // 实例化的炮塔
    private GameObject turretInstance_none; 
    private Vector3 startPosition; // 拖动起始位置
    [SerializeField] private float creatCost = 0;
    public AudioClip soundClip;
    private AudioSource audioSource;

    private void Start()
    {
        audioSource = GetComponent<AudioSource>();
        audioSource.clip = soundClip;
    }

    private void OnMouseDown()
    {
        startPosition = transform.position;
        turretInstance_none = Instantiate(turretPrefab_none, startPosition, Quaternion.identity);
        //turretInstance.SetActive(false);
    }

    private void OnMouseDrag()
    {
        Vector3 currentPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        currentPosition.z = 0f;
        turretInstance_none.transform.position = currentPosition;
    }

    private void OnMouseUp()
    {
        Vector3 currentPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        Vector3 PlacePosition;
        currentPosition.z = 0f;
        //Destroy(turretInstance_none);
        for (int i = 0; i < towers.Length; i++)
        {
            PlacePosition = towers[i].transform.position;
            if ((PlacePosition - currentPosition).magnitude < 1f)
            {
                PlacePosition.x += 1.23f;
                PlacePosition.y += 0.75f;
                Destroy(turretInstance_none);
                if(MoneyManager.Money>= creatCost)
                {
                    turretInstance = Instantiate(turretPrefab_first, PlacePosition, Quaternion.identity);
                    MoneyManager.Money -= creatCost;
                    audioSource.PlayOneShot(soundClip);
                }
                else
                {
                    return;
                }
            }
            Destroy(turretInstance_none);
        }
    }
}


